import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'dart:core';
import 'package:flutter_app_05/widget/stateful_widget_extends.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class NetsResponseData<T> extends Object {
  final bool isSuccess;
  final String message;
  final T resData;

  const NetsResponseData(
      {this.isSuccess = false, this.message = '', this.resData});
}

Dio global_dio = Dio();

class RequestPaths extends Object {
  static final urlBase = 'http://221.2.155.180:30039';



  /// api:
///膨胀系数
  static final balance_extend = '/balance/Extend/sel';

  ///阻力-比摩阻
  static final balance_comDn = '/balance/comDn/selrmb';
  //阻力
  static final balance_comPa = '/balance/comPa/sel';
  //水泵选型
  static final balance_Pump = '/balance/Pump/sel';
  //热水器计算
  static final balance_comHeat = '/balance/comHeat/sel';
  //管径
  static final balance_comDnsel = '/balance/comDn/sel';
  //更多1
  static final forum_getlcb = '/balance/forum/getlcb';

  //更多2
  static final forum_getother = '/balance/forum/getother';
  //登录
  static final URL_LOGIN = '/balance/forum/login';
}

/// 只提供一个dio 这个类内完成网络请求相关的配置 以及返回结果内容的检查
/// 外部始终会拿到用NetsResponseData包裹的数据
class Nets extends Object {
  /// dio单利是否初始化完成
  static bool _isInitDio = false;

  /// dio单利的getter
  static Dio get dio => Nets.getDio();

  /// 检查返回结果(服务器返回的内容)
  ///
  /// 每个项目可能不同
  static NetsResponseData checkResponse(Response response) {
    // var responseData = jsonDecode(response.data.toString());

    var responseData =  new Map<String, dynamic>.from(response.data);
    int code = responseData["code"];
    String a=responseData['msg'];
    if (code == 0) {
      print("responseData:miaojinlong");
     var m= NetsResponseData(isSuccess: true, message: responseData['msg'], resData: responseData);
      print("zheshishuju "+m.message);
      return m;

    } else {
      print("responseData:rimnima");
      return NetsResponseData(isSuccess: false, message: responseData['msg'], resData: responseData);
    }
  }

  /// 对网络数据的ui响应 + 数据的后续处理
  ///
  /// state必须混入TStateMixin
  static Future<dynamic> resolveData(Response<dynamic> response,
      {state: TStateMixin,
      bool showSuccessInfo = false,
      bool showErrorInfo = true,
      ValueChanged<bool> whenClosed}) async {
    print("aaaaaaaaaaaaaa"+response.data.isSuccess);
    if (response.data.isSuccess) {

      if (state != null &&
          state.mounted &&
          state is TStateMixin &&
          showSuccessInfo) {
        state
            .tShowMessage(message: response.data.message)
            .closed
            .whenComplete(() {
          if (state != null && state.mounted && whenClosed != null) {
            whenClosed(true);
          }
        });
      }
      return response.data.resData;
    } else {
      print("miaojinl"+response.data.isSuccess);
      if (state != null && state is TStateMixin && showErrorInfo) {
        state
            .tShowMessage(message: response.data.message)
            .closed
            .whenComplete(() => () {
                  if (state != null && state.mounted && whenClosed != null) {
                    whenClosed(false);
                  }
                });
      }
      print( response.data.resData.toString()+"");
      return response.data.resData;
    }
  }

  static Dio getDio() {

    Dio dio = Dio();
    dio.options.baseUrl = RequestPaths.urlBase;
     // global_dio.options.contentType = 'application/x-www-form-urlencoded';
     // global_dio.options.contentType = 'application/json; charset=utf-8';
    dio.options.contentType = 'application/json';
    dio.interceptors.add(
      LogInterceptor(
        request: false,
        requestHeader: true,
        requestBody: true,
        responseBody: true,
        responseHeader: false,
      ),
    );

    // dio.interceptors.add(
    //     InterceptorsWrapper (
    //         onRequest: (options, handler)async{
    //        // EasyLoading.show(status: "");
    //
    //           return handler.next(options);
    //         },
    //       onResponse: (response,handler)async{
    //         // EasyLoading.dismiss();
    //         print(response.data.toString()+"aaaaaaaaaaaaaaaaaaa");
    //         return Nets.checkResponse(response);
    //       },
    //       onError: (DioError e, handler)async{
    //
    //       return   handler.resolve(
    //         Response(requestOptions: e.requestOptions,data:  '网络出问题了！\n ${e.toString()}',)
    //
    //       );//continue
    //
    // }
    //
    //     )
    // );


     _isInitDio = true;

    return dio;
  }


  static Dio getDio1() {

    Dio dio = Dio();
    dio.options.baseUrl = RequestPaths.urlBase;
    // global_dio.options.contentType = 'application/x-www-form-urlencoded';
    // global_dio.options.contentType = 'application/json; charset=utf-8';
    dio.options.contentType = 'application/json';
    dio.interceptors.add(
      LogInterceptor(
        request: false,
        requestHeader: true,
        requestBody: true,
        responseBody: true,
        responseHeader: false,
      ),
    );

    dio.interceptors.add(
        InterceptorsWrapper (
            onRequest: (options, handler)async{
              // EasyLoading.show(status: "");

              return handler.next(options);
            },
            onResponse: (response,handler)async{
              // EasyLoading.dismiss();
              print(response.data.toString()+"aaaaaaaaaaaaaaaaaaa");
              return Nets.checkResponse(response);
            },
            onError: (DioError e, handler)async{

              return   handler.resolve(
                  Response(requestOptions: e.requestOptions,data:  '网络出问题了！\n ${e.toString()}',)

              );//continue

            }

        )
    );


    _isInitDio = true;

    return dio;
  }
}
